package com.lej.core.utils

import android.app.Activity
import android.content.Context
import android.graphics.drawable.Drawable
import android.widget.ImageView
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestBuilder
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.BitmapImageViewTarget
import com.bumptech.glide.request.target.CustomViewTarget
import com.bumptech.glide.request.transition.Transition
import com.lej.core.R
import com.lej.core.base.app
import com.lej.core.utils.extention.dp2Px
import com.lej.core.utils.extention.getColorCompat
import com.lej.core.utils.extention.safe
import com.lej.core.widget.drawable.TextDrawable
import com.qmuiteam.qmui.util.QMUIDisplayHelper

fun load(url: String?, view: ImageView) {
    Glide.with(view).load(url).into(view)
}

fun load(resId: Int?, view: ImageView) {
    Glide.with(view).load(resId)
        .diskCacheStrategy(DiskCacheStrategy.NONE) // 不使用磁盘缓存
        .into(view)
}

fun load(url: String?, @DrawableRes defaultImg: Int, view: ImageView) {
    Glide.with(view)
        .load(url)
        .diskCacheStrategy(DiskCacheStrategy.NONE) // 不使用磁盘缓存
        .apply(RequestOptions.noTransformation().error(defaultImg).placeholder(defaultImg))
        .into(view)
}

fun load(url: String?, view: ImageView,width:Int,height:Int){
    Glide.with(view).load(url).override(width,height).into(view)
}

fun load(url: String?, @DrawableRes defaultImg: Int, @DrawableRes errorImg: Int, view: ImageView) {
    Glide.with(view)
        .load(url)
        .diskCacheStrategy(DiskCacheStrategy.NONE) // 不使用磁盘缓存
        .apply(RequestOptions.noTransformation().error(errorImg).placeholder(defaultImg))
        .into(view)
}

fun load(context: Context, url: String?, @DrawableRes defaultImg: Int, view: ImageView) {
    Glide.with(context)
        .load(url)
        .apply(RequestOptions.noTransformation().error(defaultImg).placeholder(defaultImg))
        .into(view)
}

fun load(fragment: Fragment, url: String?, @DrawableRes defaultImg: Int, view: ImageView) {
    Glide.with(fragment)
        .load(url)
        .apply(RequestOptions.noTransformation().error(defaultImg).placeholder(defaultImg))
        .into(view)
}

fun ImageView.load(@DrawableRes res: Int) {
    Glide.with(this).load(res).into(this)
}

fun ImageView.loadWithText(
    url: String?,
    loadingText: String? = null,
    @ColorInt
    textColor: Int = app.getColorCompat(R.color.qmui_config_color_50_white),
    @DrawableRes errorImg: Int? = null,
    withFade: Boolean = false,
    placeholderScaleType: ImageView.ScaleType? = ImageView.ScaleType.CENTER_INSIDE,
    block: (RequestBuilder<*>.() -> RequestBuilder<*>)? = null
) {
    load(
        url,
        errorImg = errorImg,
        withFade = withFade,
        placeholderScaleType = placeholderScaleType
    ) {
        block?.invoke(this)
        placeholder(
            TextDrawable(
                context,
                15.dp2Px().toFloat(),
                textColor,
                loadingText.safe()
            )
        )
    }
}

/**
 * 将图片加载最大的分辨率改为屏幕分辨率
 */
fun changeUrl(url: String?): String {
    val width = QMUIDisplayHelper.getScreenWidth(app)
    val height = QMUIDisplayHelper.getScreenHeight(app)
    return changeImageUrlWithQiniuSize(url, width, height)
}

fun changeImageUrlWithQiniuSize(
    url: String?,
    width: Int,
    height: Int,
    blurRadius: Int = 0
): String {
    if (url == null) return ""
    if (url.contains(".gif")) return url

    var outUrl = "$url?imageMogr2/thumbnail/!${width}x${height}r/auto-orient"
    if (blurRadius > 0)
        outUrl =
            if (outUrl.contains("?")) "${outUrl}&imageMogr2/blur/${blurRadius}x50" else "$outUrl?imageMogr2/blur/${blurRadius}x50"

    return outUrl
}

/**会清理参数*/
fun String.replaceQiniuImageMogr2Params(pairs: Map<String, String?>): String {
    if (contains(".mp4")) return this
    val str = if (contains('?')) StringBuffer(this.dropLastWhile { it != '?' }
        .trimEnd('?')) else StringBuffer(
        this
    )
    if (pairs.isNotEmpty()) {
        str.append("?imageMogr2")
        pairs.forEach {
            str.append('/')
            str.append(it.key)
            str.append('/')
            str.append(it.value)
            str.append("/auto-orient")
        }
    }
    return str.toString()
}

fun main(args: Array<String>) {
    print(
        "https://mini01.jiuyan.info/2020-02-14-194859-353.jpeg?imageslim".changeQiniuSize(
            100,
            100
        )
    )
}

/**会清理参数*/
fun String.replaceQiniuImageMogr2Params(vararg pairs: Pair<String, String>): String {
    if (contains(".mp4")) return this
    return replaceQiniuImageMogr2Params(hashMapOf(*pairs))
}

/**[ratherThan] true的时候  返回的图片只会大于提供的宽高*/
fun String.changeQiniuSize(width: Int = 0, height: Int = 0, ratherThan: Boolean = false): String {
    if (isNullOrEmpty()) return this
    if (contains(".mp4")) return this
    var lWidth = width
    var lHeight = height
    if (lWidth == 0 || lHeight == 0) {
        lWidth = QMUIDisplayHelper.getScreenWidth(app)
        lHeight = QMUIDisplayHelper.getScreenHeight(app)
    }
    ///取宽缩放比和高缩放比的较小值   !${width}x${height}r 的话是较大值

    val ratioStr = if (ratherThan) "!${lWidth}x${lHeight}r" else "${lWidth}x${lHeight}"
    return replaceQiniuImageMogr2Params("thumbnail" to "$ratioStr/auto-orient")
}

fun String.qiniuSlim(): String {
    if (contains(".mp4")) return this
    val str = if (contains('?')) StringBuffer(this.dropLastWhile { it != '?' }
        .trimEnd('?')) else StringBuffer(
        this
    )
    str.append("?imageslim")
    return str.toString()
}

fun Context.preloadImage(url: String?) {
    if (url.isNullOrEmpty()) return
    Glide.with(this).load(url)
        .diskCacheStrategy(DiskCacheStrategy.DATA)
        .preload()
}

fun ImageView.load(
    url: String?,
    @DrawableRes defaultImg: Int? = null,
    @DrawableRes errorImg: Int? = null,
    withFade: Boolean = false,
    placeholderScaleType: ImageView.ScaleType? = null,
    callBack: ((Drawable) -> Unit)? = null,
    block: (RequestBuilder<*>.() -> RequestBuilder<*>)? = null
) {
    if (isDestroyedActivity(context)) return
    Glide.with(this)
        .load(url)
        .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
        .apply {
            defaultImg?.let { placeholder(it) }
            (errorImg ?: defaultImg)?.let { error(it) }
            if (withFade) transition(DrawableTransitionOptions().crossFade())
            block?.invoke(this)
        }.let {
            if (placeholderScaleType != null || callBack != null)
                it.into(object : CustomViewTarget<ImageView, Drawable>(this) {
                    var scaleType = this@load.scaleType
                    override fun onLoadFailed(errorDrawable: Drawable?) {
                        placeholderScaleType?.let { view.scaleType = it }
                        this@load.setImageDrawable(errorDrawable)
                    }

                    override fun onResourceCleared(placeholder: Drawable?) {
                        placeholderScaleType?.let { view.scaleType = it }
                        this@load.setImageDrawable(placeholder)
                    }

                    override fun onResourceLoading(placeholder: Drawable?) {
                        super.onResourceLoading(placeholder)
                        placeholderScaleType?.let { view.scaleType = it }
                        this@load.setImageDrawable(placeholder)
                    }

                    override fun onResourceReady(
                        resource: Drawable,
                        transition: Transition<in Drawable>?
                    ) {
                        this@load.scaleType = scaleType
                        val didSucceedTransition =
                            transition?.transition(resource, BitmapImageViewTarget(view)) ?: false
                        if (!didSucceedTransition) view.setImageDrawable(resource)
                        callBack?.invoke(resource)
                    }

                })
            else it.into(this)
        }
}

fun Context.urlToBitmap(url: String) = Glide.with(this).asBitmap().load(url).submit().get()

/**
 * 判断Activity是否Destroy
 */
fun isDestroyedActivity(mActivity: Context?): Boolean {
    return if (mActivity is Activity?) mActivity == null || mActivity.isFinishing || mActivity.isDestroyed
    else false
}